package websocket

import (
	"server/pkg/debug"
	"sync"
)

type userConnManager struct {
	UserId  string
	UserMap sync.Map // map[conn_id]UserConn
}

func newUserConnManager(userId string) *userConnManager {
	return &userConnManager{UserId: userId, UserMap: sync.Map{}}
}

func (m *userConnManager) AddConn(conn *UserConn) {
	m.UserMap.Store(conn.ConnId, conn)
}

func (m *userConnManager) DelConn(connId string) {
	m.UserMap.Delete(connId)
}

func (m *userConnManager) ConnCount() int {
	onlineCnt := 0
	m.UserMap.Range(func(key, item any) bool {
		onlineCnt = onlineCnt + 1
		return true
	})
	return onlineCnt
}

func (m *userConnManager) SendAll(msg []byte) {
	m.UserMap.Range(func(key, item any) bool {
		user := item.(*UserConn)
		err := user.Send(msg)
		if err != nil {
			debug.DebugPrint("userConnManager SendAll err", err)
		}
		return true
	})
}
